Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

Solution:

  1. public class Solution {
  2. public int longestConsecutive(int[] nums) {
  3. int max = 0;
  4. Set<Integer> set = new HashSet<Integer>();
  5. for (int i = 0; i < nums.length; i++) {
  6. set.add(nums[i]);
  7. }
  8. for (int i = 0; i < nums.length; i++) {
  9. int count = 1;
  10. // look left
  11. int num = nums[i];
  12. while (set.contains(--num)) {
  13. count++;
  14. set.remove(num);
  15. }
  16. // look right
  17. num = nums[i];
  18. while (set.contains(++num)) {
  19. count++;
  20. set.remove(num);
  21. }
  22. max = Math.max(max, count);
  23. }
  24. return max;
  25. }
  26. }